package com.thunbu.thunbu_meeting_system.service


import com.thunbu.lib_common.utils.HttpLogInterceptor
import com.thunbu.lib_common.utils.TokenInterceptor
import com.thunbu.thunbu_meeting_system.BuildConfig

import okhttp3.HttpUrl

import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

internal object MainNet {

    private var okHttpClient: OkHttpClient

    private var retrofit: Retrofit
    const val DEFAULT_MILLISECONDS: Long = 30000

    init {
        val okHttpClientBuilder = OkHttpClient.Builder()
        okHttpClientBuilder.hostnameVerifier { hostname, session -> true }
        okHttpClient = okHttpClientBuilder
            .readTimeout(DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS)
            .writeTimeout(DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS)
            .connectTimeout(DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS)
            .addInterceptor(TokenInterceptor())
            .addInterceptor(HttpLogInterceptor("==>Net"))
            .build()

        retrofit = Retrofit.Builder()
            .client(okHttpClient)
            .baseUrl(BuildConfig.BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build()

    }


    fun resetBase(cloudUrl: String) {
        if (!retrofit.baseUrl().equals(HttpUrl.get(cloudUrl))) {
            retrofit = retrofit.newBuilder().client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl(cloudUrl).build()
        }
    }


    fun <T> server(clazz: Class<T>): T {
        return retrofit.create(clazz)//retrofit.create(clazz)
    }
}